package org.yan.stock.server.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public abstract class StockUtil {
	
	private static final String MAIN_URL = "http://hq.sinajs.cn/list=";
	
	private static final String ALTER_URL = "http://61.172.207.163/list=";
	
	private static int BUFF_SIZE = 512;
	
	public static String[] getStocks(String stockCodes) {
		String stockStr = requestStock(MAIN_URL + stockCodes);
		//if the domain changed, try requesting with ip
		if("".equals(stockStr)) {
			stockStr = requestStock(ALTER_URL + stockCodes);
		}
		String[] stockArr = stockStr.trim().split(";");
		for(int i = 0; i < stockArr.length; i++) {
			stockArr[i] = stockArr[i].substring(stockArr[i].indexOf("\"") + 1, stockArr[i].length() - 1);
		}
		return stockArr;
	}
	
	public static String requestStock(String stUrl) {
		byte[] buff = new byte[BUFF_SIZE];
		StringBuilder sb = new StringBuilder("");
		InputStream in = null;
		try {
			URL url = new URL(stUrl);
			URLConnection conn = url.openConnection();
			in = conn.getInputStream();
			while(in.read(buff) > 0) {
				sb.append(new String(buff,"GBK"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString().trim();
	}
	
	public static void main(String[] args) {
		String[] strArr = getStocks("sh000001");
		for(String str : strArr) {
			System.out.println(str);
		}
	}

}
